package io.nads.api.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.nads.api.ASR;
import io.nads.utils.HttpRequestUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 七牛云语音识别(ASR)工具类
 * 使用新的OpenAI兼容API端点和Bearer Token认证
 */
@Data
@Slf4j
public class QiniuASR implements ASR {
    
    private final String apiKey;
    private final String baseUrl;
    
    public QiniuASR(String apiKey, String baseUrl) {
        this.apiKey = apiKey;
        this.baseUrl = baseUrl;
        
        log.info("QiniuASR初始化成功, baseUrl={}", baseUrl);
    }
    
    /**
     * 发送带Bearer Token认证的POST请求
     * @param url 请求URL
     * @param data 请求数据
     * @return 响应结果
     */
    private JSONObject postWithBearerToken(String url, Map<String, Object> data) {
        return HttpRequestUtil.postWithBearerToken(url, data, apiKey, "QiniuASR/1.0", "QiniuASR");
    }
    
    /**
     * 语音识别请求
     * @param audioUrl 音频文件URL
     * @return 识别结果
     */
    public AsrResult asrRequest(String audioUrl) {
        // 构建新API格式的请求体
        Map<String, Object> body = new HashMap<>();
        body.put("model", "asr");
        
        Map<String, Object> audio = new HashMap<>();
        // 根据URL后缀判断音频格式
        String format = audioUrl.toLowerCase().endsWith(".wav") ? "wav" : "mp3";
        audio.put("format", format);
        audio.put("url", audioUrl);
        
        body.put("audio", audio);
        
        JSONObject response = postWithBearerToken(baseUrl, body);
        
        if (response != null) {
            AsrResult result = new AsrResult();
            result.setSuccess(true);
            result.setData(response);
            return result;
        } else {
            AsrResult result = new AsrResult();
            result.setSuccess(false);
            result.setErrorMessage("ASR请求失败");
            return result;
        }
    }

    @Override
    public String parse(String url) {
        AsrResult result = asrRequest(url);
        return result.getText();
    }

    /**
     * ASR响应结果封装类
     */
    @Data
    public static class AsrResult {
        private boolean success;
        private String errorMessage;
        private JSONObject data;
        
        /**
         * 获取识别的文本内容
         * @return 识别文本
         */
        public String getText() {
            if (success && data != null) {
                // 根据新的七牛云ASR API响应格式提取文本
                // 响应格式: {"data": {"result": {"text": "识别结果"}}}
                JSONObject dataObj = data.getJSONObject("data");
                if (dataObj != null) {
                    JSONObject resultObj = dataObj.getJSONObject("result");
                    if (resultObj != null) {
                        return resultObj.getStr("text", "");
                    }
                }
            }
            return "";
        }
        
        /**
         * 获取请求ID
         * @return 请求ID
         */
        public String getRequestId() {
            if (success && data != null) {
                return data.getStr("reqid", "");
            }
            return "";
        }
    }
}